#pragma once

#include<iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<cstring>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstdlib>
#include<string>
#include<unistd.h>
class udpClient{
private:
    //服务器ip
    std::string ser_ip;
    //服务器端口号
    int ser_prot;
    //socket文件描述符
    int sock;
public:
    udpClient(std::string ip = "127.0.0.1",int port = 8080) :ser_ip(ip),ser_prot(port),sock(-1)
    {}
    void initClient() {
        //创建socket文件描述符
        sock = socket(AF_INET, SOCK_DGRAM, 0);
        if (sock < 0) {
            std::cerr << "sock error!" << std::endl;
        }
//        struct sockaddr_in local;
//        local.sin_family = AF_INET;         //使用IPV4
//        local.sin_port = htons(ser_prot);   //prot主机序列转为网络序列
//        local.sin_addr.s_addr = inet_addr(ser_ip.c_str()); //服务器IP
////       socklen_t len = sizeof(local);

//        //绑定端口号
//        //将sockaddr_in类型的参数强转位sockaddr才能传入bind
//        if (bind(sock, (struct sockaddr*)&local, len) < 0) {
//            std::cerr << "bind error!" << std::endl;
//            exit(1);
//        }
//
    }
    void start() {
        std::string msg;
        struct sockaddr_in peer;
        peer.sin_family = AF_INET;
        peer.sin_port = htons(ser_prot);
        peer.sin_addr.s_addr = inet_addr(ser_ip.c_str());
        while (true) {
              std::cout<<"Please Enter Msg# :";
              getline(std::cin,msg);
              sendto(sock,msg.c_str(),msg.size(),0,(struct sockaddr*)&peer,sizeof(peer));
              char echo[64];
              ssize_t s = recvfrom(sock,echo,sizeof(echo),0,nullptr,nullptr);
              if(s > 0){
                  echo[s] = 0;
                  std::cout<<"server# "<<echo<<std::endl;
              }
//            msg[0] = '\0';
//            struct sockaddr_in end_point;
//            socklen_t len = sizeof(end_point);
//            //接收对端发来的信息
//            ssize_t s = recvfrom(sock,msg,sizeof(msg)-1,0,(struct sockaddr*)&end_point,&len);
//            if(s > 0){
//                msg[s] = '\0';
//                std::cout<<"client# "<<msg<<std::endl;
//                std::string echo =msg;
//                echo += "[serve echo!]";
//                //服务器向客户端回显信息
//                sendto(sock,echo.c_str(),echo.size(),0,(struct sockaddr*)&end_point,len);
//            }            
        }
    }
    ~udpClient() {
        close(sock);
    }
};

